<template>
  <div class="add-person-wrapper">
    <div class="add-person-card">
      <h2>添加人员</h2>
      <form @submit.prevent="submitForm" class="person-form">
        <!-- username（必填） -->
        <div class="form-group">
          <label for="username">用户名（username） *</label>
          <input
              type="text"
              id="username"
              v-model="formData.username"
              placeholder="请输入用户名"
              required
          />
        </div>

        <!-- 密码字段（可选，但如果填写必须同时填写确认密码） -->
        <div class="form-group">
          <label for="password">密码（password）</label>
          <input
              type="password"
              id="password"
              v-model="formData.password"
              placeholder="请输入密码（可选）"
          />
        </div>

        <div class="form-group">
          <label for="confirmPassword">确认密码（confirmPassword）</label>
          <input
              type="password"
              id="confirmPassword"
              v-model="formData.confirmPassword"
              placeholder="请再次输入密码（可选）"
          />
        </div>

        <!-- firstName（可选） -->
        <div class="form-group">
          <label for="firstName">名字（firstName）</label>
          <input
              type="text"
              id="firstName"
              v-model="formData.firstName"
              placeholder="请输入名字"
          />
        </div>

        <!-- lastName（可选） -->
        <div class="form-group">
          <label for="lastName">姓氏（lastName）</label>
          <input
              type="text"
              id="lastName"
              v-model="formData.lastName"
              placeholder="请输入姓氏"
          />
        </div>

        <!-- email（可选） -->
        <div class="form-group">
          <label for="email">邮箱（email）</label>
          <input
              type="email"
              id="email"
              v-model="formData.email"
              placeholder="请输入邮箱"
          />
        </div>

        <!-- phone（可选） -->
        <div class="form-group">
          <label for="phone">电话（phone）</label>
          <input
              type="tel"
              id="phone"
              v-model="formData.phone"
              placeholder="请输入电话"
          />
        </div>

        <!-- gender（可选） -->
        <div class="form-group">
          <label for="gender">性别（gender）</label>
          <input
              type="text"
              id="gender"
              v-model="formData.gender"
              placeholder="请输入性别"
          />
        </div>

        <!-- photo（可选） -->
        <div class="form-group">
          <label for="photo">头像链接（photo）</label>
          <input
              type="url"
              id="photo"
              v-model="formData.photo"
              placeholder="请输入头像链接（可选）"
          />
        </div>
        <!-- authorities（必填，多选） -->
        <div class="form-group">
          <label>权限（authorities） *</label>
          <select multiple v-model="formData.authorities" required>
            <option value="ADMIN">管理员（admin）</option>
            <option value="BUSINESS">商家（business）</option>
            <option value="USER">顾客（user）</option>
          </select>
          <small style="color: red;">* 至少选择一个权限</small>
        </div>
        <!-- 提交按钮 -->
        <div class="button-group">
          <button type="button" class="cancel-btn" @click="goBack">取消</button>
          <button type="submit" class="submit-btn" :disabled="isSubmitting">
            {{ isSubmitting ? '提交中...' : '添加人员' }}
          </button>
        </div>

        <!-- 消息提示 -->
        <p v-if="message" :class="['message', message.type]">{{ message.text }}</p>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();

// 表单数据
const formData = ref({
  username: '',          // 必填
  password: '',          // 可选
  confirmPassword: '',   // 可选
  firstName: '',         // 可选
  lastName: '',          // 可选
  email: '',             // 可选
  phone: '',             // 可选
  gender: '',            // 可选
  photo: '',             // 可选
  authorities: [],       // 必填，多选权限，如 ['admin', 'business']
});

// 提交状态
const isSubmitting = ref(false);

// 消息提示
const message = ref(null);

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// JWT 解析函数
const getSub = (token) => {
  try {
    const parts = token.split('.');
    if (parts.length !== 3) throw new Error('Invalid JWT format');

    const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')));
    return payload.sub || null;
  } catch (error) {
    console.error('Failed to parse JWT:', error);
    return null;
  }
};

// 提交表单函数
const submitForm = async () => {
  // 重置消息
  message.value = null;

  // 验证密码一致性（如果填写了其中一个密码字段）
  if (formData.value.password || formData.value.confirmPassword) {
    if (formData.value.password !== formData.value.confirmPassword) {
      message.value = { type: 'error', text: '两次输入的密码不一致！' };
      return;
    }

    // 验证密码长度
    if (formData.value.password.length < 6) {
      message.value = { type: 'error', text: '密码长度至少6位！' };
      return;
    }
  }

  try {
    // 获取 JWT token
    const token = sessionStorage.getItem('jwt');
    if (!token) {
      message.value = { type: 'error', text: '用户未登录！' };
      return;
    }

    // 解析用户名
    const curUsername = getSub(token);
    if (!curUsername) {
      message.value = { type: 'error', text: '用户信息获取失败！' };
      return;
    }

    // 准备提交的数据
    const payload = {
      username: formData.value.username,
      authorities: formData.value.authorities.map(auth => ({ name: auth })),
      // 仅在用户填写了密码时才包含密码字段
      ...(formData.value.password && { password: formData.value.password }),
      // 可选字段，仅在有值时包含
      ...(formData.value.firstName && { firstName: formData.value.firstName }),
      ...(formData.value.lastName && { lastName: formData.value.lastName }),
      ...(formData.value.email && { email: formData.value.email }),
      ...(formData.value.phone && { phone: formData.value.phone }),
      ...(formData.value.gender && { gender: formData.value.gender }),
      ...(formData.value.photo && { photo: formData.value.photo }),
    };

    // 使用 axios 直接发送请求
    const response = await axios.post('/persons', payload, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token.slice(1,-1)}`  // 添加认证令牌
      }
    });

    if (response.status === 200 || response.status === 201) {
      message.value = { type: 'success', text: '人员添加成功！' };
      formData.value = {
        username: '',
        password: '',
        confirmPassword: '',
        firstName: '',
        lastName: '',
        email: '',
        phone: '',
        gender: '',
        photo: '',
        authorities: []
      };

      // 3秒后自动返回
      setTimeout(() => {
        router.go(-1);
      }, 3000);
    }
  } catch (err) {
    console.error('添加人员失败:', err);

    if (err.response) {
      // 服务器返回的错误
      const errorMsg = err.response.data?.message || '添加人员失败';
      message.value = { type: 'error', text: errorMsg };
    } else if (err.request) {
      // 网络错误
      message.value = { type: 'error', text: '网络错误，请检查连接！' };
    } else {
      // 其他错误
      message.value = { type: 'error', text: '添加人员失败，请重试！' };
    }
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
/* 全局居中布局 */
.add-person-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

/* 卡片样式 */
.add-person-card {
  width: 100%;
  max-width: 600px;
  padding: 30px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 24px;
}

.person-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

label {
  font-weight: bold;
  color: #555;
}

input,
select {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus,
select:focus {
  outline: none;
  border-color: #007bff;
}

/* 多选下拉框特殊样式 */
select {
  height: 150px;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.submit-btn {
  flex: 1;
  padding: 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover:not(:disabled) {
  background-color: #0056b3;
}

.submit-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.cancel-btn {
  flex: 1;
  padding: 12px;
  background-color: #f0f0f0;
  color: #333;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}

/* 消息提示 */
.message {
  margin-top: 15px;
  padding: 12px;
  border-radius: 6px;
  text-align: center;
  font-size: 14px;
}

.message.success {
  background-color: #e6ffed;
  color: #1a7324;
  border: 1px solid #b7eb8f;
}

.message.error {
  background-color: #ffebee;
  color: #c62828;
  border: 1px solid #ffa4a4;
}
</style>